package com.umfwechat.lightprogram.controller.my;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringUtil;

/**
 * 代理商开户	开户；修改代理商信息 修改
 * @author llb
 *
 */
@Controller
@RequestMapping("/agentManagement")
public class AgentOpenController {
	private static Logger logger = LoggerFactory.getLogger(AgentOpenController.class);
	
	/**
	 * 代理商开户---开户
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/openAgent")
	@ResponseBody
	public JSONObject openAgent(HttpServletRequest request, HttpServletResponse response){	
		JSONObject json= new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "成功");
		//获取请求参数
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param=JSONObject.fromObject(reqJSON);
		//登录代理商编号
		String loginAgentId = param.optString("loginAgentId");
		//登录代理商编号
		String agentId = param.optString("agentId");
		//代理商全称
		String agentName = param.optString("agentName");
		//代理商简称
		String agentShortName = param.optString("agentShortName");
		//组织机构码
		String registrationNo = param.optString("registrationNo");
		//工商登记号
		String busiRegistNum = param.optString("busiRegistNum");
		//联系人
		String userName = param.optString("userName");
		//联系人手机号
		String userMobile = param.optString("userMobile");
		//登陆账号
		String assistId = param.optString("assistId");
		//管理员邮箱
		String email = param.optString("email");
		//查询管理员基本信息
		Map<String, Object> res = getAgentManager(assistId, "");
		String retCode=(String)res.get("retCode");
		if(!"0000".equals(retCode)){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
//		if(!"00060516".equals(retCode)){
//			if("0000".equals(retCode)){
//				json.put(CommonConsts.RETCODE, "00434103");
//				json.put(CommonConsts.RETMSG, "登陆账号已存在");
//			}else{
//				json.put(CommonConsts.RETCODE, "00434101");
//				json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
//			}
//			return json;
//		}
		List<Map> list=(List<Map>)res.get("agentManagerList");
		if(list.size()>0){
			json.put(CommonConsts.RETCODE, "00434103");
			json.put(CommonConsts.RETMSG, "登陆账号已存在");
			return json;
		}
		//查询当前登陆代理商的信息
		//查询代理商基本信息
		Map<String, Object> resQ=getAgentByPrimaryKey(loginAgentId,"0");
		String retCodeQ=(String)resQ.get("retCode");
		if(!"0000".equals(retCodeQ)){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		Map<String ,Map<String ,String>> agentList = (Map<String ,Map<String ,String>>) resQ.get("agentMap");
		Map<String ,String> agentData = (Map<String, String>) agentList.get(loginAgentId);
		//新增代理商
		Map<String, Object> resC = createAgent(agentId,agentData,agentName,agentShortName,registrationNo,busiRegistNum,userName,userMobile,assistId,email);
		String retCodeC=(String)resC.get("retCode");
		if(!"0000".equals(retCodeC)){
//			if("00060511".equals(retCodeC)){
//				json.put(CommonConsts.RETCODE, "0001");
//				json.put(CommonConsts.RETMSG, "代理商已存在");
//			}else {
				json.put(CommonConsts.RETCODE, "00434101");
				json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
//			}
			return json;
		}
//		String currentAgentId=(String) resC.get("agentId");
//		//新增代理商管理员
//		Map<String, Object> resM = createAgentManager(assistId,currentAgentId,userName,userMobile,email);
//		String retCodeM=(String)resM.get("retCode");
//		if(!"0000".equals(retCodeM)){
//			json.put(CommonConsts.RETCODE, "0001");
//			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
//			return json;
//		}
		return json;
	}
	/**
	 * 修改代理商信息---修改
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateAgent")
	@ResponseBody
	public JSONObject updateAgent(HttpServletRequest request, HttpServletResponse response){	
		JSONObject json= new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "成功");
		//获取请求参数
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param=JSONObject.fromObject(reqJSON);
		//要修改的理商编号
		String agentId = param.optString("agentId");
		//代理商全称
		String agentName = param.optString("agentName");
		//代理商简称
		String agentShortName = param.optString("agentShortName");
		//组织机构码
		String registrationNo = param.optString("registrationNo");
		//工商登记号
		String busiRegistNum = param.optString("busiRegistNum");
		//联系人
		String userName = param.optString("userName");
		//联系人手机号
		String userMobile = param.optString("userMobile");
		//登陆账号
		String assistId = param.optString("assistId");
		//管理员邮箱
		String email = param.optString("agentMail");
		//查询管理员信息
//		Map<String, Object> resM = getAgentManager(assistId, agentId);
//		String retCodeM=(String)resM.get("retCode");
//		if(!"0000".equals(retCodeM)){
//			json.put(CommonConsts.RETCODE, "00434101");
//			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
//			return json;
//		}
//		List<Map<String,String>> agentManagerList=(List<Map<String,String>>) resM.get("agentManagerList");
//		Map<String, String> agentManager = agentManagerList.get(0);
//		//修改管理员信息
//		Map<String, Object> resU = updateAgentManager(agentManager,assistId, agentId, email);
//		String retCodeU=(String)resU.get("retCode");
//		if(!"0000".equals(retCodeU)){
//			if("00060527".equals(retCodeU)){
//				json.put(CommonConsts.RETCODE, "00434103");
//				json.put(CommonConsts.RETMSG, "登陆账号已存在");
//			}else{
//				json.put(CommonConsts.RETCODE, "00434101");
//				json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
//			}
//			return json;
//		}
		////修改代理商基本信息
		Map<String, Object> updateAgent = updateAgent(agentId, agentName, agentShortName, registrationNo, busiRegistNum, userName, userMobile, assistId, email);
		String retCodeUA=(String)updateAgent.get("retCode");
		if(!"0000".equals(retCodeUA)){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		return json;
	}
	//查询管理员信息
	private Map<String, Object>  getAgentManager(String assistId,String agentId){
		//查询管理员基本信息
		Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
		if(StringUtil.isNotEmpty(assistId)){
			req.put("id", assistId);
		}
		req.put("userName", "admin");
		if(StringUtil.isNotEmpty(agentId)){
			req.put("agentId", agentId);
		}
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentManager");
			logger.info("【查询管理员基本信息】接口入参："+req.toString()+"请求路径为"+url);
			res = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);
		} catch (Exception e) {
			logger.info("查询代理商列表server接口异常",e);
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		if(res==null){
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		logger.info("【查询管理员基本信息】接口出参："+res.toString());
		return res;
	}
	//根据主键查询代理商基本信息
	private Map<String, Object> getAgentByPrimaryKey(String agentId,String isQryMer) {
		Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
		req.put("agentId", agentId);
		//是否附带直拓商户信息0-不查询,1-查询
		req.put("isQryMer", "0");
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgent");
			logger.info("【根据主键查询代理商详情】接口入参："+req.toString()+"请求路径为"+url);
			res = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);
		} catch (Exception e) {
			logger.info("查询代理商列表server接口异常",e);
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		if(res==null){
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		logger.info("【根据主键查询代理商详情】接口出参："+res.toString());
		return res;
	}
	//新增代理商
	private Map<String, Object> createAgent(String agentId, Map<String,String> agentData, String agentName,
			String agentShortName, String registrationNo, String busiRegistNum,
			String userName, String userMobile, String assistId, String email) {
		Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
		req.putAll(agentData);
		req.put("agentId", agentId);
		req.put("agentName", agentName);
		req.put("agentShortName",agentShortName);
		req.put("organizationId",registrationNo);
		req.put("licenseNo",busiRegistNum);
		req.put("linkmanName",userName);
		req.put("linkmanMobileId",userMobile);
		//代理商级别为当前代理商级别+1
		String agentLevel = agentData.get("agentLevel");
		Integer agentLevel1=Integer.parseInt(agentLevel)+1;
		req.put("agentLevel",agentLevel1.toString());
		req.put("supAgentId",agentData.get("agentId"));//当前代理商编号
		req.remove("agentId");	//删除父级代理商id
//		agentData1.put("agentLevel","1");//开通一级使用
//		agentData1.remove("agentId");//开通一级使用
		req.put("isCreateManager","1");//0-不开通,1-开通
		//登陆账号信息
		req.put("id", assistId);
		req.put("managerType", "0");//0-admin 1-普通操作员
		req.put("userName", "admin");
		req.put("mobileId", assistId);
		req.put("email", email);
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.createAgent");
			logger.info("【新增代理商】接口入参："+req.toString()+"请求路径为"+url);
			res = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);
		} catch (Exception e) {
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			logger.error("【新增代理商接口】异常" , e);
			return res;
		}
		if(res==null){
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		logger.info("【新增代理商】接口出参："+res.toString());
		return res;
	}
	//修改代理商管理员
	private Map<String, Object> updateAgentManager(Map<String, String> agentManager, String assistId, String agentId, String email) {
		Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
		req.putAll(agentManager);
		req.put("id", assistId);
		req.put("agentId", agentId);
		req.put("managerType", "0");//0-admin 1-普通操作员
		req.put("userName", "admin");
		req.put("mobileId", assistId);
		req.put("email", email);
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.updateAgentManager");
			logger.info("【更新代理商管理员】接口入参："+req.toString()+"请求路径为"+url);
			res = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);
		} catch (Exception e) {
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			logger.info("【更新代理商管理员接口】异常" , e);
			return res;
		}
		if(res==null){
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		logger.info("【更新代理商管理员】接口出参："+res.toString());
		return res;
	}
	//修改代理商基本信息
	private Map<String, Object> updateAgent( String agentId,String agentName,
			String agentShortName, String registrationNo, String busiRegistNum,
			String userName, String userMobile, String assistId, String email) {
		Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
		req.put("updateMode", "1");
		req.put("agentId", agentId);
		req.put("agentName", agentName);
		req.put("agentShortName",agentShortName);
		req.put("organizationId",registrationNo);
		req.put("licenseNo",busiRegistNum);
		req.put("linkmanName",userName);
		req.put("linkmanMobileId",userMobile);
		req.put("isUpdateManager","1");//是否修改代理商管理员(admin)0-不修改,1-修改
		req.put("id",assistId);
		req.put("mobileId",assistId);
		req.put("email",email);
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.updateAgent");
			logger.info("【更新代理商】接口入参："+req.toString()+"请求路径为"+url);
			res = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);
		} catch (Exception e) {
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			logger.info("【更新代理商管理员接口】异常" , e);
			return res;
		}
		if(res==null){
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		logger.info("【更新代理商】接口出参："+res.toString());
		return res;
	}
	/**
	 * 新增时获取代理商编号
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getAgentId")
	@ResponseBody
	public JSONObject getAgentId(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json= new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "成功");
		//获取请求参数
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param=JSONObject.fromObject(reqJSON);
		//当前代理商编号
		String agentLevel = param.optString("loginAgentLevel");
		Integer level=Integer.parseInt(agentLevel)+1;
		Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
		req.put("agentLevel", level.toString());
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.getAgentId");
			logger.info("【获取代理商编号】接口入参："+req.toString()+"请求路径为"+url);
			res = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			logger.error("【获取代理商编号】异常" , e);
			return json;
		}
		if(res==null){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		logger.info("【获取代理商编号】接口出参："+res.toString());
		String retCode=(String)res.get("retCode");
		if(!"0000".equals(retCode)){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		String agentId = (String) res.get("agentId");
		json.put("agentId", agentId);
		return json;
	}
	
	

}
